package controllers

import (
	"strconv"
	"strings"
	"time"

	"git.oschina.net/goxiang2/web/admin/models"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func TimeToStr(t int64) string {
	return time.Unix(t, 0).Format("2006-01-02 15:04:05")
}

func StrToTime(str string) int64 {
	loc, _ := time.LoadLocation("Local")
	the_time, err := time.ParseInLocation("2006-01-02 15:04:05", str, loc)
	if err == nil {
		return the_time.Unix()
	} else {
		return 0
	}
}

func (c *UserController) Get() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/login")
		return
	}

	c.Data["title"] = beego.AppConfig.String("apptitle")
	c.Data["username"] = userinfo.(*LoginInfo).Username

	user_permission := models.GetPermission(userinfo.(*LoginInfo).Username)
	if (user_permission & (1 << uint(models.ModelUser))) == 0 {
		c.Ctx.Redirect(302, "/index")
		return
	}
	data := getIndex(user_permission)
	for k, v := range data {
		c.Data[k] = v
	}

	users, _ := models.GetUserlist()
	permissions, _ := models.GetRolelist()

	c.Data["users"] = users
	c.Data["permissions"] = permissions
	c.Data["token"] = models.GetToken()
	c.TplName = "user.ace"
}

func (c *UserController) Post() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/login")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	username := c.GetString("username")
	user := models.GetUserByUsername(username)
	if user != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "用户已存在"}
		c.ServeJSON()
		return
	}

	u := new(models.User)
	u.Username = c.GetString("username")
	i, _ := strconv.Atoi(c.GetString("permission"))
	u.Role = int64(i)
	u.Password = c.GetString("password")
	u.CreateTs = time.Now().Unix()
	u.LastLoginTs = time.Now().Unix()

	_, err := models.AddUser(u)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "创建用户成功"}
	c.ServeJSON()

	go models.SaveLog(username, "创建用户", &map[string]interface{}{"username": u.Username, "permission": i})
}

func (c *UserController) Put() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/login")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	user := models.GetUserByUsername(c.GetString("oldUsername"))
	if user == nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "用户不存在"}
		c.ServeJSON()
		return
	}

	u := new(models.User)
	u.Id = user.Id
	u.Username = c.GetString("username")
	i, _ := strconv.Atoi(c.GetString("permission"))
	u.Role = int64(i)
	u.Password = c.GetString("password")

	_, err := models.UpdateUser(u)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "更新用户成功"}
	c.ServeJSON()

	go models.SaveLog(userinfo.(*LoginInfo).Username, "修改用户", &map[string]interface{}{"username": u.Username, "permission": i})
}

func (c *UserController) Delete() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/login")
		return
	}

	if !models.CheckPermission(userinfo.(*LoginInfo).Username, models.ModelUser) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "没有操作权限"}
		c.ServeJSON()
		return
	}

	var ids []int64
	usernames := c.GetString("usernames")
	array := strings.Split(usernames, ",")
	for i := 0; i < len(array); i++ {
		user := models.GetUserByUsername(array[i])
		if user == nil {
			c.Data["json"] = &map[string]interface{}{"status": false, "info": "用户[" + array[i] + "]不存在"}
			c.ServeJSON()
			return
		}
		ids = append(ids, user.Id)
	}

	for i := 0; i < len(ids); i++ {
		models.DelUserById(ids[i])
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "删除用户成功"}
	c.ServeJSON()

	go models.SaveLog(userinfo.(*LoginInfo).Username, "删除用户", &map[string]interface{}{"usernames": usernames})
}
